package org.mspring.mlog.action.blog;

import org.mspring.mlog.ServiceContext;
import org.mspring.mlog.common.ArticleDto;
import org.mspring.mlog.entity.Article;
import org.mspring.mlog.entity.em.ArticleStatus;
import org.mspring.mlog.service.ArticleService;
import org.mspring.mlog.service.ConfigService;
import org.mspring.nbee.db.dao.sql.builder.part.condition.Operator;
import org.mspring.nbee.db.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.db.dao.sql.builder.part.condition.impl.SimpleCondition;
import org.mspring.nbee.db.dao.sql.pager.OrderType;
import org.mspring.nbee.db.dao.sql.pager.PageResult;
import org.mspring.nbee.db.dao.sql.pager.Pager;
import org.mspring.nbee.web.Action;
import org.mspring.nbee.web.support.QueryParam;
import org.mspring.nbee.web.support.WebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-03 15:17
 */
@Action("blogIndexAction")
public class IndexAction {
    private ConfigService configService;
    private ArticleService articleService;
    private ServiceContext serviceContext;

    @RequestMapping({"/index", "/", ""})
    public String index(WebContext context, Model model) {
        Pager pager = context.getPager();
        pager.addOrder("id", OrderType.DESC);
        List<SqlCondition> conditions = context.buildSqlConditions(model,
                new QueryParam("title", Operator.LIKE),
                new QueryParam("category", Operator.EQ)
        );
        conditions.add(new SimpleCondition("status", Operator.EQ, ArticleStatus.NORMAL));
        PageResult<Article> tempResult = articleService.list(conditions, pager);
        PageResult<ArticleDto> articleResult = new PageResult<>();
        articleResult.setPager(tempResult.getPager());
        articleResult.setTotal(tempResult.getTotal());
        articleResult.setData(ArticleDto.fromArticles(tempResult.getData(), serviceContext));
        model.addAttribute("articleResult", articleResult);
        return "theme:/index";
    }

    @Autowired
    public void setConfigService(ConfigService configService) {
        this.configService = configService;
    }

    @Autowired
    public void setArticleService(ArticleService articleService) {
        this.articleService = articleService;
    }

    @Autowired
    public void setServiceContext(ServiceContext serviceContext) {
        this.serviceContext = serviceContext;
    }
}
